package game.web.dao.impl;

import game.web.dao.TicketDAO;
import game.web.dao.dto.TicketDTO;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import projectx.core.base.ProjectXSystemException;
import projectx.core.dao.AbstractDAO;
import projectx.core.dao.DataAccessException;
import projectx.core.dao.ExceptionHandler;
import projectx.core.dao.Parameter;
import projectx.core.dao.impl.PreparedStatementBuilder;

public class TicketDAOImpl extends AbstractDAO implements TicketDAO {

	public TicketDAOImpl() throws ProjectXSystemException {
		super();
	}

	@Override
	public TicketDTO execute(Parameter param) throws DataAccessException {
		System.out.println("TicketDAOImpl  start");
		TicketDTO dto = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		int count = 0;
		String sql = null;
		try {
			_builder = (PreparedStatementBuilder) SqlLoader.getBuilders().get(
					"TicketDAO_SELECT");
			List paramKeys = new ArrayList();
			sql = _builder.getSql(param, paramKeys);
			ps = _builder.createStatement(_conn, sql, false, false);
			_builder.setParameter(ps, param, paramKeys);

			/**************************************************
			Statement stmt = _conn.createStatement();
			rs = stmt.executeQuery("SELECT seqid,createdate,lastupdate,updateby FROM ticket WHERE seqid = 1");
			while (rs.next()) {
				System.out.print(rs.getString(1));
				System.out.print(rs.getString(2));
			}*/
			
			debugSql();

			rs = ps.executeQuery();

			if (rs.next()) {
				String result1 = getString(rs.getString(1));
				String result2 = getString(rs.getString(2));
				String result3 = getString(rs.getString(3));
				String result4 = getString(rs.getString(4));
				dto = new TicketDTO();
				dto.setSeqid(result1);
				dto.setCreatedate(result2);
				dto.setLastupdate(result3);
				dto.setUpdateby(result4);

				count++;
			}

			if (count == 1 && rs.next()) {
				count++;
			}
		} catch (Exception e) {
			errorSql(e);
			_exHandler.handleQueryException(e, ExceptionHandler.UNKNOWN);
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (ps != null) {
					ps.close();
				}
			} catch (SQLException e) {
				logError(e);
			}
		}
		if (count > 1) {
			_exHandler.handleQueryException(null, ExceptionHandler.MULTIFOUND);
		}
		return dto;
	}

}
